#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sudoku.h"

#define CELL_WIDTH 15

int get_input(int ary[],int aryLen,FILE* fp )
{
   int _a[9];
   int c=0;
   while (1)
   {
      int rst=fscanf(fp,"%d ",_a);
      if ( _a[0]==-1)
         break;

      rst = fscanf(fp,"%d %d %d %d %d %d %d %d",
         _a+1,_a+2,_a+3,_a+4,_a+5,_a+6,_a+7,_a+8)+1;

      for (int i=0;i<rst && c+i<aryLen;i++)
         ary[c+i]=_a[i];
      c += rst;
      if (c>aryLen )
      {
         c=aryLen;
         break;
      }
      if ( rst != 9 || c==81)
         break;
   }
   return c;
}

void print_sameChar(char c,int count)
{
    for (int i=0;i<count;i++)
        printf("%c",c);
}
void print_string_same_width(char* s, int width)
{
    int n0=strlen(s);
    int n1=(width-n0)/2;
    int n2=(width-n0-n1);
    print_sameChar(' ',n1);
    printf("%s",s);
    print_sameChar(' ',n2);
}

// the d always >='0' and <='9'
void print_num(int d, int width)
{
    char s[8];
    s[0]= (d==0)? ' ' : d+'0';
    s[1]=0;
    print_string_same_width(s,width);
}

void print_mask(BitsType m, int width,bool zip_mode)
{
    char buf[32];
    char *p=buf;
    *p++ ='[';
    for (int i=1;i<=9;i++)
    {
        if ( (m & (1<<i)) )
        {   sprintf(p,"%d|",i); p+=2;   }
    }
    *(p-1)=']'; // 将最后的'|'改为']'
    if ( zip_mode)
        printf("%s",buf);
    else
        print_string_same_width(buf,width);
}

void print_line(char first,char others,int segment_len, int count)
{
    for (int i=0;i<9;i++)
    {
        printf("%c",first);
        print_sameChar(others,segment_len);
    }
    printf("%c\n",first);
}

void printStatus(void *p,Cell cells[9][9])
{
    for (int row=0;row<9;row++)
    {
        print_line('+','-',CELL_WIDTH, 9);
        print_line('|',' ',CELL_WIDTH, 9);
        for (int col=0;col<9;col++)
        {
            printf("|");
            if ( cells[row][col].flag== KNOWN )
                print_num(cells[row][col].num,CELL_WIDTH);
            else
                print_mask(cells[row][col].candidate, CELL_WIDTH,false);
        }
        printf("|\n");
        print_line('|',' ',CELL_WIDTH, 9);
    }
    print_line('+','-',CELL_WIDTH, 9);
}

void printResult(void *p,Cell cells[9][9])
{
    for (int row=0;row<9;row++)
    {
        print_line('+','-',CELL_WIDTH, 9);
        print_line('|',' ',CELL_WIDTH, 9);
        for (int col=0;col<9;col++)
        {
            printf("|");
            print_num(cells[row][col].num,CELL_WIDTH);
        }
        printf("|\n");
        print_line('|',' ',CELL_WIDTH, 9);
    }
    print_line('+','-',CELL_WIDTH, 9);
}

